<?php
session_start();

/**
 * Script used to set the index of an element in the databse
 */

// Return json encoded data
header ('Content-type: application/json');

require_once '../core/db.php';

// Check if user owns the page:
if(isset($_SESSION['user'])) {
    $sql = 'SELECT userId from sitePages WHERE pageId = ?';
    $sth = $db->prepare ($sql);
    $sth->execute (array ($_POST['siteId']));
    $tmp= $sth->fetch (PDO::FETCH_ASSOC);
    $ok = ($tmp['userId']==$_SESSION['user']) ? 1:0;

    // If user is logged in and own the page, update index:
    if($ok==1) {
        $sql = 'UPDATE siteElement SET elementIndex=? WHERE elementId=?';
        $sth = $db->prepare ($sql);
        $res = $sth->execute (array ($_POST['index'], $_POST['id']));
        if ($res==1) {
        	echo json_encode (array ('ok'=>'OK'));
        }
        else {
        	echo json_encode (array ('fail'=>'Kunne ikke oppdatere elementets index i databasen.'));
        }
    }
    else {
        echo json_encode (array('fail' => 'Du kan ikke sortere en side uten å eie den.'));
    }
}
else {
    echo json_encode (array ('fail'=>'Du kan ikke sortere en side uten å være logget inn.'));
}
?>